﻿using System;
using System.Collections.Generic;
using System.Linq;
using _5E.Utils.CollectionHelper.GenericExtension;

namespace _5E.Utils.DbHelper.EasySQL.Creator
{
    /// <summary>
    /// 程序说明：创建插入SQL
    /// 创建作者：ahl5esoft
    /// 创建时间：2012-04-16
    /// </summary>
    class InsertCreator : BaseCreator, ICustomColumn
    {
        #region 变量

        private const string INSERT_SQL_FORMAT = "INSERT INTO {0}({1}) VALUES({2})";

        private string[] m_Columns = null;

        #endregion

        #region 构造函数

        public InsertCreator(string tableName, Dictionary<string, string> allColumns)
            : base(tableName, allColumns) { }

        #endregion

        #region 实例方法

        public ICustomColumn SetColumns(string[] propertyNames)
        {
            this.m_Columns = propertyNames;
            return this;
        }

        protected override string CreateSQL()
        {
            var columnString = this.GetColumnString();
            var propertyString = this.GetPrameterString();
            var sql = string.Format(INSERT_SQL_FORMAT, this.TableName, columnString, propertyString);
            return sql;
        }

        private string GetColumnString()
        {
            var propertyNames = this.m_Columns.Exchange(this.AllColumns.Keys.ToArray());
            var columNames = Array.ConvertAll(propertyNames, this.GetColumnName);
            var columnString = ToColumnString(columNames);
            return columnString;
        }

        private string GetPrameterString()
        {
            var properties = Array.ConvertAll(this.m_Columns, f => string.Format(":{0}", f));
            var prameterString = ToColumnString(properties);
            return prameterString;
        }

        protected override void Reset()
        {
            this.m_Columns = null;
        }

        #endregion
    }
}
